/**
 * 
 */
package com.gopay.checkorder.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.CuccPayConstants;
import com.gopay.common.constants.bank.CuccPayOrderStatus;
import com.gopay.common.constants.bank.CuccPayQureyRespone;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.cuccpay.ebank.CuccPayMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.common.util.DateUtils;
import com.gopay.remote.bank.BankInteractRemoteService;

/**
 * @CheckOrderCuccPayB2cImpl.java
 * @author Ryan
 * @2013-11-14 上午11:33:56 www.gopay.com.cn Inc.All rights reserved.
 */
public class CheckOrderCuccPayImpl implements BankOrderService {

    private Logger logger = Logger.getLogger("CUCCPAY");
    @Resource(name = "bankClient")
    private BankInteractRemoteService bankClient;
    @Override
    public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {

        CheckOrderResult checkOrderResult = new CheckOrderResult();
        checkOrderResult.setSuccess(false);
        checkOrderResult.setOrderId(bankOrder.getOrderId());
        CuccPayMessage message = new CuccPayMessage();
        message.setOrderId(bankOrder.getOrderId());
        message.setBankOrderId(bankOrder.getOutOrderId());
        message.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
        message.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
        message.setOrderDate(DateUtils.format(bankOrder.getSendBankTm(), "yyyyMMdd"));
        message.setBank(bankOrder.getBankCode());

        Result result = new Result();
        try {
            result = bankClient.query(message);
        } catch (Exception e) {
            logger.error("bankClient fail.", e);
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
            checkOrderResult.setErrMsg("银行对账异常");
            return checkOrderResult;
        }

        if (result == null || !result.isSuccess()) {
            logger.error("bankClient fail.");
            if(result ==null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())){
            	BankCountDownLatch.failIncrease(bankOrder.getBankCode());
            	checkOrderResult.setCommunicateError(true);
			}
            logger.error(ToStringBuilder.reflectionToString(result, ToStringStyle.DEFAULT_STYLE));
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
            checkOrderResult.setErrMsg("系统返回对账结果为空");
            return checkOrderResult;
        }

        CuccPayMessage res = (CuccPayMessage) result.getDefaultModel();
        if (res == null) {
            // 查询订单为空
            logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + ProcCodeConstants.PROC_CODE_100E5062+ " err:bis query is null.");
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
            checkOrderResult.setErrMsg("银行返回对账结果为空");
        }

        if (!StringUtils.equals(CuccPayConstants.TRADE_RETURN_SUCCESS, res.getQueryResult())) {
            // 查询订单错误
            logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + res.getQueryResult() + " err:"+ CuccPayQureyRespone.getName(res.getQueryResult()));
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
            checkOrderResult.setErrMsg(CuccPayQureyRespone.getName(res.getQueryResult()));
            return checkOrderResult;
        }

        checkOrderResult.setOrderId(bankOrder.getOrderId());
        checkOrderResult.setAmount(new BigDecimal(res.getPayAmount()));
        //成功处理
        if (StringUtils.equals(CuccPayConstants.ORDER_STATE_SUCCESS, res.getOrderState())) {
            checkOrderResult.setSuccess(true);
            InAccInfo accInfo = new InAccInfo();
            accInfo.setOrderId(bankOrder.getOrderId());
            accInfo.setAmount(new BigDecimal(res.getPayAmount()));
            accInfo.setRetCode("00");
            accInfo.setCardType(BankCardType.Unknown.toString());
            checkOrderResult.setAccInfo(accInfo);
            logger.error("联通沃B2C订单" + bankOrder.getOrderId() + "的交易" + CuccPayOrderStatus.getName(res.getOrderState()));
        } 
      //失败处理
        else if(StringUtils.equals(CuccPayConstants.ORDER_STATE_CLOSED, res.getOrderState())){      	        	
        	checkOrderResult.setBankFailure(true);
             checkOrderResult.setErrMsg(CuccPayOrderStatus.getName(res.getOrderState()));
             logger.error("联通沃B2C订单" + bankOrder.getOrderId() + "的交易" + CuccPayOrderStatus.getName(res.getOrderState()));
        }
        else {
            logger.error("联通沃B2C订单" + bankOrder.getOrderId() + "的交易" + CuccPayOrderStatus.getName(res.getOrderState()));
            String errMsg = CuccPayOrderStatus.getName(res.getOrderState());
            if (errMsg != null) {
                checkOrderResult.setErrMsg(errMsg);
            } else {
                checkOrderResult.setErrMsg("银行返回订单未查到");
            }

        }

        return checkOrderResult;
    }
	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public BaseMessage dayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public List<CheckOrderResult> checkDayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}

}
